home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 21 / AACD 21.iso / AACD / Utilities / Ghostscript / src / stream.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-01-01  |  30.3 KB  |  1,215 lines

  1. /* Copyright (C) 1989, 2000 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of AFPL Ghostscript.
  4.   
  5.   AFPL Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author or
  6.   distributor accepts any responsibility for the consequences of using it, or
  7.   for whether it serves any particular purpose or works at all, unless he or
  8.   she says so in writing.  Refer to the Aladdin Free Public License (the
  9.   "License") for full details.
  10.   
  11.   Every copy of AFPL Ghostscript must include a copy of the License, normally
  12.   in a plain ASCII text file named PUBLIC.  The License grants you the right
  13.   to copy, modify and redistribute AFPL Ghostscript, but only under certain
  14.   conditions described in the License.  Among other things, the License
  15.   requires that the copyright notice and this notice be preserved on all
  16.   copies.
  17. */
  18.  
  19. /*$Id: stream.c,v 1.8 2000/09/19 19:00:51 lpd Exp $ */
  20. /* Stream package for Ghostscript interpreter */
  21. #include "stdio_.h"        /* includes std.h */
  22. #include "memory_.h"
  23. #include "gdebug.h"
  24. #include "gpcheck.h"
  25. #include "stream.h"
  26. #include "strimpl.h"
  27.  
  28. /* Forward declarations */
  29. private int sreadbuf(P2(stream *, stream_cursor_write *));
  30. private int swritebuf(P3(stream *, stream_cursor_read *, bool));
  31. private void stream_compact(P2(stream *, bool));
  32.  
  33. /* Structure types for allocating streams. */
  34. public_st_stream();
  35. public_st_stream_state();    /* default */
  36. /* GC procedures */
  37. private 
  38. ENUM_PTRS_WITH(stream_enum_ptrs, stream *st) return 0;
  39. case 0:
  40. if (st->foreign)
  41.     ENUM_RETURN(NULL);
  42. else if (st->cbuf_string.data != 0)
  43.     ENUM_RETURN_STRING_PTR(stream, cbuf_string);
  44. else
  45.     ENUM_RETURN(st->cbuf);
  46. ENUM_PTR3(1, stream, strm, prev, next);
  47. ENUM_PTR(4, stream, state);
  48. case 5: return ENUM_CONST_STRING(&st->file_name);
  49. ENUM_PTRS_END
  50. private RELOC_PTRS_WITH(stream_reloc_ptrs, stream *st)
  51. {
  52.     byte *cbuf_old = st->cbuf;
  53.  
  54.     if (cbuf_old != 0 && !st->foreign) {
  55.     long reloc;
  56.  
  57.     if (st->cbuf_string.data != 0) {
  58.         RELOC_STRING_VAR(st->cbuf_string);
  59.         st->cbuf = st->cbuf_string.data;
  60.     } else
  61.         RELOC_VAR(st->cbuf);
  62.     reloc = cbuf_old - st->cbuf;
  63.     /* Relocate the other buffer pointers. */
  64.     st->srptr -= reloc;
  65.     st->srlimit -= reloc;    /* same as swptr */
  66.     st->swlimit -= reloc;
  67.     }
  68.     RELOC_VAR(st->strm);
  69.     RELOC_VAR(st->prev);
  70.     RELOC_VAR(st->next);
  71.     RELOC_VAR(st->state);
  72.     RELOC_CONST_STRING_VAR(st->file_name);
  73. }
  74. RELOC_PTRS_END
  75. /* Finalize a stream by closing it. */
  76. /* We only do this for file streams, because other kinds of streams */
  77. /* may attempt to free storage when closing. */
  78. private void
  79. stream_finalize(void *vptr)
  80. {
  81.     stream *const st = vptr;
  82.  
  83.     if_debug2('u', "[u]%s 0x%lx\n",
  84.           (!s_is_valid(st) ? "already closed:" :
  85.            st->is_temp ? "is_temp set:" :
  86.            st->file == 0 ? "not file:" :
  87.            "closing file:"), (ulong) st);
  88.     if (s_is_valid(st) && !st->is_temp && st->file != 0) {
  89.     /* Prevent any attempt to free the buffer. */
  90.     st->cbuf = 0;
  91.     st->cbuf_string.data = 0;
  92.     sclose(st);        /* ignore errors */
  93.     }
  94. }
  95.  
  96. /* Dummy template for streams that don't have a separate state. */
  97. private const stream_template s_no_template = {
  98.     &st_stream_state, 0, 0, 1, 1, 0
  99. };
  100.  
  101. /* ------ Generic procedures ------ */
  102.  
  103. /* Allocate a stream and initialize it minimally. */
  104. void
  105. s_init(stream *s, gs_memory_t * mem)
  106. {
  107.     s->memory = mem;
  108.     s->report_error = s_no_report_error;
  109.     s->error_string[0] = 0;
  110.     s->prev = s->next = 0;    /* clean for GC */
  111.     s->file_name.data = 0;    /* ibid. */
  112.     s->close_strm = false;    /* default */
  113.     s->close_at_eod = true;    /* default */
  114. }
  115. stream *
  116. s_alloc(gs_memory_t * mem, client_name_t cname)
  117. {
  118.     stream *s = gs_alloc_struct(mem, stream, &st_stream, cname);
  119.  
  120.     if_debug2('s', "[s]alloc(%s) = 0x%lx\n",
  121.           client_name_string(cname), (ulong) s);
  122.     if (s == 0)
  123.     return 0;
  124.     s_init(s, mem);
  125.     return s;
  126. }
  127.  
  128. /* Allocate a stream state and initialize it minimally. */
  129. void
  130. s_init_state(stream_state *st, const stream_template *template,
  131.          gs_memory_t *mem)
  132. {
  133.     st->template = template;
  134.     st->memory = mem;
  135.     st->report_error = s_no_report_error;
  136. }
  137. stream_state *
  138. s_alloc_state(gs_memory_t * mem, gs_memory_type_ptr_t stype,
  139.           client_name_t cname)
  140. {
  141.     stream_state *st = gs_alloc_struct(mem, stream_state, stype, cname);
  142.  
  143.     if_debug3('s', "[s]alloc_state %s(%s) = 0x%lx\n",
  144.           client_name_string(cname),
  145.           client_name_string(stype->sname),
  146.           (ulong) st);
  147.     if (st)
  148.     s_init_state(st, NULL, mem);
  149.     return st;
  150. }
  151.  
  152. /* Standard stream initialization */
  153. void
  154. s_std_init(register stream * s, byte * ptr, uint len, const stream_procs * pp,
  155.        int modes)
  156. {
  157.     s->template = &s_no_template;
  158.     s->cbuf = ptr;
  159.     s->srptr = s->srlimit = s->swptr = ptr - 1;
  160.     s->swlimit = ptr - 1 + len;
  161.     s->end_status = 0;
  162.     s->foreign = 0;
  163.     s->modes = modes;
  164.     s->cbuf_string.data = 0;
  165.     s->position = 0;
  166.     s->bsize = s->cbsize = len;
  167.     s->strm = 0;        /* not a filter */
  168.     s->is_temp = 0;
  169.     s->procs = *pp;
  170.     s->state = (stream_state *) s;    /* hack to avoid separate state */
  171.     s->file = 0;
  172.     s->file_name.data = 0;    /* in case stream is on stack */
  173.     if_debug4('s', "[s]init 0x%lx, buf=0x%lx, len=%u, modes=%d\n",
  174.           (ulong) s, (ulong) ptr, len, modes);
  175. }
  176.  
  177.  
  178. /* Set the file name of a stream, copying the name. */
  179. /* Return <0 if the copy could not be allocated. */
  180. int
  181. ssetfilename(stream *s, const byte *data, uint size)
  182. {
  183.     byte *str =
  184.     (s->file_name.data == 0 ?
  185.      gs_alloc_string(s->memory, size + 1, "ssetfilename") :
  186.      gs_resize_string(s->memory,
  187.               (byte *)s->file_name.data,    /* break const */
  188.               s->file_name.size,
  189.               size + 1, "ssetfilename"));
  190.  
  191.     if (str == 0)
  192.     return -1;
  193.     memcpy(str, data, size);
  194.     str[size] = 0;
  195.     s->file_name.data = str;
  196.     s->file_name.size = size + 1;
  197.     return 0;
  198. }
  199.  
  200. /* Return the file name of a stream, if any. */
  201. /* There is a guaranteed 0 byte after the string. */
  202. int
  203. sfilename(stream *s, gs_const_string *pfname)
  204. {
  205.     pfname->data = s->file_name.data;
  206.     if (pfname->data == 0) {
  207.     pfname->size = 0;
  208.     return -1;
  209.     }
  210.     pfname->size = s->file_name.size - 1; /* omit terminator */
  211.     return 0;
  212. }
  213.  
  214. /* Implement a stream procedure as a no-op. */
  215. int
  216. s_std_null(stream * s)
  217. {
  218.     return 0;
  219. }
  220.  
  221. /* Discard the contents of the buffer when reading. */
  222. void
  223. s_std_read_reset(stream * s)
  224. {
  225.     s->srptr = s->srlimit = s->cbuf - 1;
  226. }
  227.  
  228. /* Discard the contents of the buffer when writing. */
  229. void
  230. s_std_write_reset(stream * s)
  231. {
  232.     s->swptr = s->cbuf - 1;
  233. }
  234.  
  235. /* Flush data to end-of-file when reading. */
  236. int
  237. s_std_read_flush(stream * s)
  238. {
  239.     while (1) {
  240.     s->srptr = s->srlimit = s->cbuf - 1;
  241.     if (s->end_status)
  242.         break;
  243.     s_process_read_buf(s);
  244.     }
  245.     return (s->end_status == EOFC ? 0 : s->end_status);
  246. }
  247.  
  248. /* Flush buffered data when writing. */
  249. int
  250. s_std_write_flush(stream * s)
  251. {
  252.     return s_process_write_buf(s, false);
  253. }
  254.  
  255. /* Indicate that the number of available input bytes is unknown. */
  256. int
  257. s_std_noavailable(stream * s, long *pl)
  258. {
  259.     *pl = -1;
  260.     return 0;
  261. }
  262.  
  263. /* Indicate an error when asked to seek. */
  264. int
  265. s_std_noseek(stream * s, long pos)
  266. {
  267.     return ERRC;
  268. }
  269.  
  270. /* Standard stream closing. */
  271. int
  272. s_std_close(stream * s)
  273. {
  274.     return 0;
  275. }
  276.  
  277. /* Standard stream mode switching. */
  278. int
  279. s_std_switch_mode(stream * s, bool writing)
  280. {
  281.     return ERRC;
  282. }
  283.  
  284. /* Standard stream finalization.  Disable the stream. */
  285. void
  286. s_disable(register stream * s)
  287. {
  288.     s->cbuf = 0;
  289.     s->bsize = 0;
  290.     s->end_status = EOFC;
  291.     s->modes = 0;
  292.     s->cbuf_string.data = 0;
  293.     /* The pointers in the next two statements should really be */
  294.     /* initialized to ([const] byte *)0 - 1, but some very picky */
  295.     /* compilers complain about this. */
  296.     s->cursor.r.ptr = s->cursor.r.limit = 0;
  297.     s->cursor.w.limit = 0;
  298.     s->procs.close = s_std_null;
  299.     /* Clear pointers for GC */
  300.     s->strm = 0;
  301.     s->state = (stream_state *) s;
  302.     s->template = &s_no_template;
  303.     /* Free the file name. */
  304.     if (s->file_name.data) {
  305.     gs_free_const_string(s->memory, s->file_name.data, s->file_name.size,
  306.                  "s_disable(file_name)");
  307.     s->file_name.data = 0;
  308.     }
  309.     /****** SHOULD DO MORE THAN THIS ******/
  310.     if_debug1('s', "[s]disable 0x%lx\n", (ulong) s);
  311. }
  312.  
  313. /* Implement flushing for encoding filters. */
  314. int
  315. s_filter_write_flush(register stream * s)
  316. {
  317.     int status = s_process_write_buf(s, false);
  318.  
  319.     if (status != 0)
  320.     return status;
  321.     return sflush(s->strm);
  322. }
  323.  
  324. /* Close a filter.  If this is an encoding filter, flush it first. */
  325. int
  326. s_filter_close(register stream * s)
  327. {
  328.     if (s_is_writing(s)) {
  329.     int status = s_process_write_buf(s, true);
  330.  
  331.     if (status != 0 && status != EOFC)
  332.         return status;
  333.     }
  334.     return s_std_close(s);
  335. }
  336.  
  337. /* Disregard a stream error message. */
  338. int
  339. s_no_report_error(stream_state * st, const char *str)
  340. {
  341.     return 0;
  342. }
  343.  
  344. /* Generic procedure structures for filters. */
  345.  
  346. const stream_procs s_filter_read_procs = {
  347.     s_std_noavailable, s_std_noseek, s_std_read_reset,
  348.     s_std_read_flush, s_filter_close
  349. };
  350.  
  351. const stream_procs s_filter_write_procs = {
  352.     s_std_noavailable, s_std_noseek, s_std_write_reset,
  353.     s_filter_write_flush, s_filter_close
  354. };
  355.  
  356. /* ------ Implementation-independent procedures ------ */
  357.  
  358. /* Store the amount of available data in a(n input) stream. */
  359. int
  360. savailable(stream * s, long *pl)
  361. {
  362.     return (*(s)->procs.available) (s, pl);
  363. }
  364.  
  365. /* Return the current position of a stream. */
  366. long
  367. stell(stream * s)
  368. {
  369.     /*
  370.      * The stream might have been closed, but the position
  371.      * is still meaningful in this case.
  372.      */
  373.     const byte *ptr = (s_is_writing(s) ? s->swptr : s->srptr);
  374.  
  375.     return (ptr == 0 ? 0 : ptr + 1 - s->cbuf) + s->position;
  376. }
  377.  
  378. /* Set the position of a stream. */
  379. int
  380. spseek(stream * s, long pos)
  381. {
  382.     if_debug3('s', "[s]seek 0x%lx to %ld, position was %ld\n",
  383.           (ulong) s, pos, stell(s));
  384.     return (*(s)->procs.seek) (s, pos);
  385. }
  386.  
  387. /* Switch a stream to read or write mode. */
  388. /* Return 0 or ERRC. */
  389. int
  390. sswitch(register stream * s, bool writing)
  391. {
  392.     if (s->procs.switch_mode == 0)
  393.     return ERRC;
  394.     return (*s->procs.switch_mode) (s, writing);
  395. }
  396.  
  397. /* Close a stream, disabling it if successful. */
  398. /* (The stream may already be closed.) */
  399. int
  400. sclose(register stream * s)
  401. {
  402.     stream_state *st;
  403.     int code = (*s->procs.close) (s);
  404.  
  405.     if (code < 0)
  406.     return code;
  407.     st = s->state;
  408.     if (st != 0) {
  409.     stream_proc_release((*release)) = st->template->release;
  410.     if (release != 0)
  411.         (*release) (st);
  412.     if (st != (stream_state *) s && st->memory != 0)
  413.         gs_free_object(st->memory, st, "s_std_close");
  414.     s->state = (stream_state *) s;
  415.     }
  416.     s_disable(s);
  417.     return code;
  418. }
  419.  
  420. /*
  421.  * Define the minimum amount of data that must be left in an input buffer
  422.  * after a read operation to handle filter read-ahead.  This is 1 byte for
  423.  * filters (including procedure data sources) that haven't reached EOD,
  424.  * 0 for files.
  425.  */
  426. int
  427. sbuf_min_left(const stream *s)
  428. {
  429.     return
  430.     (s->strm == 0 ? (s->end_status != CALLC ? 0 : 1) :
  431.      s->end_status == EOFC || s->end_status == ERRC ? 0 : 1);
  432. }
  433.  
  434. /*
  435.  * Implement sgetc when the buffer may be empty.  If the buffer really is
  436.  * empty, refill it and then read a byte.  Note that filters must read one
  437.  * byte ahead, so that they can close immediately after the client reads the
  438.  * last data byte if the next thing is an EOD.
  439.  */
  440. int
  441. spgetcc(register stream * s, bool close_at_eod)
  442. {
  443.     int status, left;
  444.     int min_left = sbuf_min_left(s);
  445.  
  446.     while (status = s->end_status,
  447.        left = s->srlimit - s->srptr,
  448.        left <= min_left && status >= 0
  449.     )
  450.     s_process_read_buf(s);
  451.     if (left <= min_left &&
  452.     (left == 0 || (status != EOFC && status != ERRC))
  453.     ) {
  454.     /* Compact the stream so stell will return the right result. */
  455.     stream_compact(s, true);
  456.     if (status == EOFC && close_at_eod && s->close_at_eod) {
  457.         status = sclose(s);
  458.         if (status == 0)
  459.         status = EOFC;
  460.         s->end_status = status;
  461.     }
  462.     return status;
  463.     }
  464.     return *++(s->srptr);
  465. }
  466.  
  467. /* Implementing sputc when the buffer is full, */
  468. /* by flushing the buffer and then writing the byte. */
  469. int
  470. spputc(register stream * s, byte b)
  471. {
  472.     for (;;) {
  473.     if (s->end_status)
  474.         return s->end_status;
  475.     if (!sendwp(s)) {
  476.         *++(s->swptr) = b;
  477.         return b;
  478.     }
  479.     s_process_write_buf(s, false);
  480.     }
  481. }
  482.  
  483. /* Push back a character onto a (read) stream. */
  484. /* The character must be the same as the last one read. */
  485. /* Return 0 on success, ERRC on failure. */
  486. int
  487. sungetc(register stream * s, byte c)
  488. {
  489.     if (!s_is_reading(s) || s->srptr < s->cbuf || *(s->srptr) != c)
  490.     return ERRC;
  491.     s->srptr--;
  492.     return 0;
  493. }
  494.  
  495. /* Get a string from a stream. */
  496. /* Return 0 if the string was filled, or an exception status. */
  497. int
  498. sgets(stream * s, byte * buf, uint nmax, uint * pn)
  499. {
  500.     stream_cursor_write cw;
  501.     int status = 0;
  502.     int min_left = sbuf_min_left(s);
  503.  
  504.     cw.ptr = buf - 1;
  505.     cw.limit = cw.ptr + nmax;
  506.     while (cw.ptr < cw.limit) {
  507.     int left;
  508.  
  509.     if ((left = s->srlimit - s->srptr) > min_left) {
  510.         s->srlimit -= min_left;
  511.         stream_move(&s->cursor.r, &cw);
  512.         s->srlimit += min_left;
  513.     } else {
  514.         uint wanted = cw.limit - cw.ptr;
  515.         int c;
  516.         stream_state *st;
  517.  
  518.         if (wanted >= s->bsize >> 2 &&
  519.         (st = s->state) != 0 &&
  520.         wanted >= st->template->min_out_size &&
  521.         s->end_status == 0 &&
  522.         left == 0
  523.         ) {
  524.         byte *wptr = cw.ptr;
  525.  
  526.         cw.limit -= min_left;
  527.         status = sreadbuf(s, &cw);
  528.         cw.limit += min_left;
  529.         /*
  530.          * We know the stream buffer is empty, so it's safe to
  531.          * update position.  However, we need to reset the read
  532.          * cursor to indicate that there is no data in the buffer.
  533.          */
  534.         s->srptr = s->srlimit = s->cbuf - 1;
  535.         s->position += cw.ptr - wptr;
  536.         if (status != 1 || cw.ptr == cw.limit)
  537.             break;
  538.         }
  539.         c = spgetc(s);
  540.         if (c < 0) {
  541.         status = c;
  542.         break;
  543.         }
  544.         *++(cw.ptr) = c;
  545.     }
  546.     }
  547.     *pn = cw.ptr + 1 - buf;
  548.     return (status >= 0 ? 0 : status);
  549. }
  550.  
  551. /* Write a string on a stream. */
  552. /* Return 0 if the entire string was written, or an exception status. */
  553. int
  554. sputs(register stream * s, const byte * str, uint wlen, uint * pn)
  555. {
  556.     uint len = wlen;
  557.     int status = s->end_status;
  558.  
  559.     if (status >= 0)
  560.     while (len > 0) {
  561.         uint count = s->swlimit - s->swptr;
  562.  
  563.         if (count > 0) {
  564.         if (count > len)
  565.             count = len;
  566.         memcpy(s->swptr + 1, str, count);
  567.         s->swptr += count;
  568.         str += count;
  569.         len -= count;
  570.         } else {
  571.         byte ch = *str++;
  572.  
  573.         status = sputc(s, ch);
  574.         if (status < 0)
  575.             break;
  576.         len--;
  577.         }
  578.     }
  579.     *pn = wlen - len;
  580.     return (status >= 0 ? 0 : status);
  581. }
  582.  
  583. /* Skip ahead a specified distance in a read stream. */
  584. /* Return 0 or an exception code. */
  585. /* Store the number of bytes skipped in *pskipped. */
  586. int
  587. spskip(register stream * s, long nskip, long *pskipped)
  588. {
  589.     long n = nskip;
  590.     int min_left;
  591.  
  592.     if (nskip < 0 || !s_is_reading(s)) {
  593.     *pskipped = 0;
  594.     return ERRC;
  595.     }
  596.     if (s_can_seek(s)) {
  597.     long pos = stell(s);
  598.     int code = sseek(s, pos + n);
  599.  
  600.     *pskipped = stell(s) - pos;
  601.     return code;
  602.     }
  603.     min_left = sbuf_min_left(s);
  604.     while (sbufavailable(s) < n + min_left) {
  605.     int code;
  606.  
  607.     n -= sbufavailable(s);
  608.     s->srptr = s->srlimit;
  609.     if (s->end_status) {
  610.         *pskipped = nskip - n;
  611.         return s->end_status;
  612.     }
  613.     code = sgetc(s);
  614.     if (code < 0) {
  615.         *pskipped = nskip - n;
  616.         return code;
  617.     }
  618.     --n;
  619.     }
  620.     /* Note that if min_left > 0, n < 0 is possible; this is harmless. */
  621.     s->srptr += n;
  622.     *pskipped = nskip;
  623.     return 0;
  624. }
  625.  
  626. /* Read a line from a stream.  See srdline.h for the specification. */
  627. int
  628. sreadline(stream *s_in, stream *s_out, void *readline_data,
  629.       gs_const_string *prompt, gs_string * buf,
  630.       gs_memory_t * bufmem, uint * pcount, bool *pin_eol,
  631.       bool (*is_stdin)(P1(const stream *)))
  632. {
  633.     uint count = *pcount;
  634.  
  635.     /* Most systems define \n as 0xa and \r as 0xd; however, */
  636.     /* OS-9 has \n == \r == 0xd and \l == 0xa.  The following */
  637.     /* code works properly regardless of environment. */
  638. #if '\n' == '\r'
  639. #  define LF 0xa
  640. #else
  641. #  define LF '\n'
  642. #endif
  643.  
  644.     if (count == 0 && s_out && prompt) {
  645.     uint ignore_n;
  646.     int ch = sputs(s_out, prompt->data, prompt->size, &ignore_n);
  647.  
  648.     if (ch < 0)
  649.         return ch;
  650.     }
  651.  
  652. top:
  653.     if (*pin_eol) {
  654.     /*
  655.      * We're in the middle of checking for a two-character
  656.      * end-of-line sequence.  If we get an EOF here, stop, but
  657.      * don't signal EOF now; wait till the next read.
  658.      */
  659.     int ch = spgetcc(s_in, false);
  660.  
  661.     if (ch == EOFC) {
  662.         *pin_eol = false;
  663.         return 0;
  664.     } else if (ch < 0)
  665.         return ch;
  666.     else if (ch != LF)
  667.         sputback(s_in);
  668.     *pin_eol = false;
  669.     return 0;
  670.     }
  671.     for (;;) {
  672.     int ch = sgetc(s_in);
  673.  
  674.     if (ch < 0) {        /* EOF or exception */
  675.         *pcount = count;
  676.         return ch;
  677.     }
  678.     switch (ch) {
  679.         case '\r':
  680.         {
  681. #if '\n' == '\r'        /* OS-9 or similar */
  682.             if (!is_stdin(s_in))
  683. #endif
  684.             {
  685.             *pcount = count;
  686.             *pin_eol = true;
  687.             goto top;
  688.             }
  689.         }
  690.         /* falls through */
  691.         case LF:
  692. #undef LF
  693.         *pcount = count;
  694.         return 0;
  695.     }
  696.     if (count >= buf->size) {    /* filled the string */
  697.         if (!bufmem) {
  698.         sputback(s_in);
  699.         *pcount = count;
  700.         return 1;
  701.         }
  702.         {
  703.         uint nsize = count + max(count, 20);
  704.         byte *ndata = gs_resize_string(bufmem, buf->data, buf->size,
  705.                            nsize, "sreadline(buffer)");
  706.  
  707.         if (ndata == 0)
  708.             return ERRC; /* no better choice */
  709.         buf->data = ndata;
  710.         buf->size = nsize;
  711.         }
  712.     }
  713.     buf->data[count++] = ch;
  714.     }
  715.     /*return 0; *//* not reached */
  716. }
  717.  
  718. /* ------ Utilities ------ */
  719.  
  720. /*
  721.  * Attempt to refill the buffer of a read stream.  Only call this if the
  722.  * end_status is not EOFC, and if the buffer is (nearly) empty.
  723.  */
  724. int
  725. s_process_read_buf(stream * s)
  726. {
  727.     int status;
  728.  
  729.     stream_compact(s, false);
  730.     status = sreadbuf(s, &s->cursor.w);
  731.     s->end_status = (status >= 0 ? 0 : status);
  732.     return 0;
  733. }
  734.  
  735. /*
  736.  * Attempt to empty the buffer of a write stream.  Only call this if the
  737.  * end_status is not EOFC.
  738.  */
  739. int
  740. s_process_write_buf(stream * s, bool last)
  741. {
  742.     int status = swritebuf(s, &s->cursor.r, last);
  743.  
  744.     stream_compact(s, false);
  745.     return (status >= 0 ? 0 : status);
  746. }
  747.  
  748. /* Move forward or backward in a pipeline.  We temporarily reverse */
  749. /* the direction of the pointers while doing this. */
  750. /* (Cf the Deutsch-Schorr-Waite graph marking algorithm.) */
  751. #define MOVE_BACK(curr, prev)\
  752.   BEGIN\
  753.     stream *back = prev->strm;\
  754.     prev->strm = curr; curr = prev; prev = back;\
  755.   END
  756. #define MOVE_AHEAD(curr, prev)\
  757.   BEGIN\
  758.     stream *ahead = curr->strm;\
  759.     curr->strm = prev; prev = curr; curr = ahead;\
  760.   END
  761.  
  762. /* Read from a pipeline. */
  763. private int
  764. sreadbuf(stream * s, stream_cursor_write * pbuf)
  765. {
  766.     stream *prev = 0;
  767.     stream *curr = s;
  768.     int status;
  769.  
  770.     for (;;) {
  771.     stream *strm;
  772.  
  773.     for (;;) {        /* Descend into the recursion. */
  774.         stream_cursor_read cr;
  775.         stream_cursor_read *pr;
  776.         stream_cursor_write *pw;
  777.         int left;
  778.         bool eof;
  779.  
  780.         strm = curr->strm;
  781.         if (strm == 0) {
  782.         cr.ptr = 0, cr.limit = 0;
  783.         pr = &cr;
  784.         left = 0;
  785.         eof = false;
  786.         } else {
  787.         pr = &strm->cursor.r;
  788.         left = sbuf_min_left(strm);
  789.         left = min(left, pr->limit - pr->ptr);
  790.         pr->limit -= left;
  791.         eof = strm->end_status == EOFC;
  792.         }
  793.         pw = (prev == 0 ? pbuf : &curr->cursor.w);
  794.         if_debug4('s', "[s]read process 0x%lx, nr=%u, nw=%u, eof=%d\n",
  795.               (ulong) curr, (uint) (pr->limit - pr->ptr),
  796.               (uint) (pw->limit - pw->ptr), eof);
  797.         status = (*curr->procs.process) (curr->state, pr, pw, eof);
  798.         pr->limit += left;
  799.         if_debug4('s', "[s]after read 0x%lx, nr=%u, nw=%u, status=%d\n",
  800.               (ulong) curr, (uint) (pr->limit - pr->ptr),
  801.               (uint) (pw->limit - pw->ptr), status);
  802.         if (strm == 0 || status != 0)
  803.         break;
  804.         status = strm->end_status;
  805.         if (status < 0)
  806.         break;
  807.         MOVE_AHEAD(curr, prev);
  808.         stream_compact(curr, false);
  809.     }
  810.     /* If curr reached EOD and is a filter stream, close it. */
  811.     if (strm != 0 && status == EOFC &&
  812.         curr->cursor.r.ptr >= curr->cursor.r.limit &&
  813.         curr->close_at_eod
  814.         ) {
  815.         int cstat = sclose(curr);
  816.  
  817.         if (cstat != 0)
  818.         status = cstat;
  819.     }
  820.     /* Unwind from the recursion. */
  821.     curr->end_status = (status >= 0 ? 0 : status);
  822.     if (prev == 0)
  823.         return status;
  824.     MOVE_BACK(curr, prev);
  825.     }
  826. }
  827.  
  828. /* Write to a pipeline. */
  829. private int
  830. swritebuf(stream * s, stream_cursor_read * pbuf, bool last)
  831. {
  832.     stream *prev = 0;
  833.     stream *curr = s;
  834.     int depth = 0;        /* # of non-temp streams before curr */
  835.     int status;
  836.  
  837.     /*
  838.      * The handling of EOFC is a little tricky.  There are two
  839.      * invariants that keep it straight:
  840.      *      - We only pass last = true to a stream if either it is
  841.      * the first stream in the pipeline, or it is a temporary stream
  842.      * below the first stream and the stream immediately above it has
  843.      * end_status = EOFC.
  844.      */
  845.     for (;;) {
  846.     for (;;) {
  847.         /* Move ahead in the pipeline. */
  848.         stream *strm = curr->strm;
  849.         stream_cursor_write cw;
  850.         stream_cursor_read *pr;
  851.         stream_cursor_write *pw;
  852.  
  853.         /*
  854.          * We only want to set the last/end flag for
  855.          * the top-level stream and any temporary streams
  856.          * immediately below it.
  857.          */
  858.         bool end = last &&
  859.         (prev == 0 ||
  860.          (depth <= 1 && prev->end_status == EOFC));
  861.  
  862.         if (strm == 0)
  863.         cw.ptr = 0, cw.limit = 0, pw = &cw;
  864.         else
  865.         pw = &strm->cursor.w;
  866.         if (prev == 0)
  867.         pr = pbuf;
  868.         else
  869.         pr = &curr->cursor.r;
  870.         if_debug5('s',
  871.               "[s]write process 0x%lx(%s), nr=%u, nw=%u, end=%d\n",
  872.               (ulong)curr,
  873.               gs_struct_type_name(curr->state->template->stype),
  874.               (uint)(pr->limit - pr->ptr),
  875.               (uint)(pw->limit - pw->ptr), end);
  876.         status = curr->end_status;
  877.         if (status >= 0) {
  878.         status = (*curr->procs.process)(curr->state, pr, pw, end);
  879.         if_debug5('s',
  880.               "[s]after write 0x%lx, nr=%u, nw=%u, end=%d, status=%d\n",
  881.               (ulong) curr, (uint) (pr->limit - pr->ptr),
  882.               (uint) (pw->limit - pw->ptr), end, status);
  883.         if (status == 0 && end)
  884.             status = EOFC;
  885.         if (status == EOFC || status == ERRC)
  886.             curr->end_status = status;
  887.         }
  888.         if (strm == 0 || (status < 0 && status != EOFC))
  889.         break;
  890.         if (status != 1) {
  891.         /*
  892.          * Keep going if we are closing a filter with a sub-stream.
  893.          * We know status == 0 or EOFC.
  894.          */
  895.         if (!end || !strm->is_temp)
  896.             break;
  897.         }
  898.         status = strm->end_status;
  899.         if (status < 0)
  900.         break;
  901.         if (!curr->is_temp)
  902.         ++depth;
  903.         if_debug1('s', "[s]moving ahead, depth = %d\n", depth);
  904.         MOVE_AHEAD(curr, prev);
  905.         stream_compact(curr, false);
  906.     }
  907.     /* Move back in the pipeline. */
  908.     curr->end_status = (status >= 0 ? 0 : status);
  909.     if (status < 0 || prev == 0) {
  910.         /*
  911.          * All streams up to here were called with last = true
  912.          * and returned 0 or EOFC (so their end_status is now EOFC):
  913.          * finish unwinding and then return.  Change the status of
  914.          * the prior streams to ERRC if the new status is ERRC,
  915.          * otherwise leave it alone.
  916.          */
  917.         while (prev) {
  918.         if_debug0('s', "[s]unwinding\n");
  919.         MOVE_BACK(curr, prev);
  920.         if (status >= 0)
  921.             curr->end_status = 0;
  922.         else if (status == ERRC)
  923.             curr->end_status = ERRC;
  924.         }
  925.         return status;
  926.     }
  927.     MOVE_BACK(curr, prev);
  928.     if (!curr->is_temp)
  929.         --depth;
  930.     if_debug1('s', "[s]moving back, depth = %d\n", depth);
  931.     }
  932. }
  933.  
  934. /* Move as much data as possible from one buffer to another. */
  935. /* Return 0 if the input became empty, 1 if the output became full. */
  936. int
  937. stream_move(stream_cursor_read * pr, stream_cursor_write * pw)
  938. {
  939.     uint rcount = pr->limit - pr->ptr;
  940.     uint wcount = pw->limit - pw->ptr;
  941.     uint count;
  942.     int status;
  943.  
  944.     if (rcount <= wcount)
  945.     count = rcount, status = 0;
  946.     else
  947.     count = wcount, status = 1;
  948.     memmove(pw->ptr + 1, pr->ptr + 1, count);
  949.     pr->ptr += count;
  950.     pw->ptr += count;
  951.     return status;
  952. }
  953.  
  954. /* If possible, compact the information in a stream buffer to the bottom. */
  955. private void
  956. stream_compact(stream * s, bool always)
  957. {
  958.     if (s->cursor.r.ptr >= s->cbuf && (always || s->end_status >= 0)) {
  959.     uint dist = s->cursor.r.ptr + 1 - s->cbuf;
  960.  
  961.     memmove(s->cbuf, s->cursor.r.ptr + 1,
  962.         (uint) (s->cursor.r.limit - s->cursor.r.ptr));
  963.     s->cursor.r.ptr = s->cbuf - 1;
  964.     s->cursor.r.limit -= dist;    /* same as w.ptr */
  965.     s->position += dist;
  966.     }
  967. }
  968.  
  969. /* ------ String streams ------ */
  970.  
  971. /* String stream procedures */
  972. private int
  973.     s_string_available(P2(stream *, long *)),
  974.     s_string_read_seek(P2(stream *, long)),
  975.     s_string_write_seek(P2(stream *, long)),
  976.     s_string_read_process(P4(stream_state *, stream_cursor_read *,
  977.                  stream_cursor_write *, bool)),
  978.     s_string_write_process(P4(stream_state *, stream_cursor_read *,
  979.                   stream_cursor_write *, bool));
  980.  
  981. /* Initialize a stream for reading a string. */
  982. void
  983. sread_string(register stream *s, const byte *ptr, uint len)
  984. {
  985.     static const stream_procs p = {
  986.      s_string_available, s_string_read_seek, s_std_read_reset,
  987.      s_std_read_flush, s_std_null, s_string_read_process
  988.     };
  989.  
  990.     s_std_init(s, (byte *)ptr, len, &p, s_mode_read + s_mode_seek);
  991.     s->cbuf_string.data = (byte *)ptr;
  992.     s->cbuf_string.size = len;
  993.     s->end_status = EOFC;
  994.     s->srlimit = s->swlimit;
  995. }
  996. /* Initialize a reusable stream for reading a string. */
  997. private void
  998. s_string_reusable_reset(stream *s)
  999. {
  1000.     s->srptr = s->cbuf - 1;    /* just reset to the beginning */
  1001.     s->srlimit = s->srptr + s->bsize;  /* might have gotten reset */
  1002. }
  1003. private int
  1004. s_string_reusable_flush(stream *s)
  1005. {
  1006.     s->srptr = s->srlimit = s->cbuf + s->bsize - 1;  /* just set to the end */
  1007.     return 0;
  1008. }
  1009. void
  1010. sread_string_reusable(stream *s, const byte *ptr, uint len)
  1011. {
  1012.     static const stream_procs p = {
  1013.      s_string_available, s_string_read_seek, s_string_reusable_reset,
  1014.      s_string_reusable_flush, s_std_null, s_string_read_process
  1015.     };
  1016.  
  1017.     sread_string(s, ptr, len);
  1018.     s->procs = p;
  1019.     s->close_at_eod = false;
  1020. }
  1021.  
  1022. /* Return the number of available bytes when reading from a string. */
  1023. private int
  1024. s_string_available(stream *s, long *pl)
  1025. {
  1026.     *pl = sbufavailable(s);
  1027.     if (*pl == 0 && s->close_at_eod)    /* EOF */
  1028.     *pl = -1;
  1029.     return 0;
  1030. }
  1031.  
  1032. /* Seek in a string being read.  Return 0 if OK, ERRC if not. */
  1033. private int
  1034. s_string_read_seek(register stream * s, long pos)
  1035. {
  1036.     if (pos < 0 || pos > s->bsize)
  1037.     return ERRC;
  1038.     s->srptr = s->cbuf + pos - 1;
  1039.     /* We might be seeking after a reusable string reached EOF. */
  1040.     s->srlimit = s->cbuf + s->bsize - 1;
  1041.     return 0;
  1042. }
  1043.  
  1044. /* Initialize a stream for writing a string. */
  1045. void
  1046. swrite_string(register stream * s, byte * ptr, uint len)
  1047. {
  1048.     static const stream_procs p = {
  1049.     s_std_noavailable, s_string_write_seek, s_std_write_reset,
  1050.     s_std_null, s_std_null, s_string_write_process
  1051.     };
  1052.  
  1053.     s_std_init(s, ptr, len, &p, s_mode_write + s_mode_seek);
  1054.     s->cbuf_string.data = ptr;
  1055.     s->cbuf_string.size = len;
  1056. }
  1057.  
  1058. /* Seek in a string being written.  Return 0 if OK, ERRC if not. */
  1059. private int
  1060. s_string_write_seek(register stream * s, long pos)
  1061. {
  1062.     if (pos < 0 || pos > s->bsize)
  1063.     return ERRC;
  1064.     s->swptr = s->cbuf + pos - 1;
  1065.     return 0;
  1066. }
  1067.  
  1068. /* Since we initialize the input buffer of a string read stream */
  1069. /* to contain all of the data in the string, if we are ever asked */
  1070. /* to refill the buffer, we should signal EOF. */
  1071. private int
  1072. s_string_read_process(stream_state * st, stream_cursor_read * ignore_pr,
  1073.               stream_cursor_write * pw, bool last)
  1074. {
  1075.     return EOFC;
  1076. }
  1077. /* Similarly, if we are ever asked to empty the buffer, it means that */
  1078. /* there has been an overrun (unless we are closing the stream). */
  1079. private int
  1080. s_string_write_process(stream_state * st, stream_cursor_read * pr,
  1081.                stream_cursor_write * ignore_pw, bool last)
  1082. {
  1083.     return (last ? EOFC : ERRC);
  1084. }
  1085.  
  1086. /* ------ Position-tracking stream ------ */
  1087.  
  1088. private int
  1089.     s_write_position_process(P4(stream_state *, stream_cursor_read *,
  1090.                 stream_cursor_write *, bool));
  1091.  
  1092. /* Set up a write stream that just keeps track of the position. */
  1093. void
  1094. swrite_position_only(stream *s)
  1095. {
  1096.     static byte discard_buf[50];    /* size is arbitrary */
  1097.  
  1098.     swrite_string(s, discard_buf, sizeof(discard_buf));
  1099.     s->procs.process = s_write_position_process;
  1100. }
  1101.  
  1102. private int
  1103. s_write_position_process(stream_state * st, stream_cursor_read * pr,
  1104.              stream_cursor_write * ignore_pw, bool last)
  1105. {
  1106.     pr->ptr = pr->limit;    /* discard data */
  1107.     return 0;
  1108. }
  1109.  
  1110. /* ------ Filter pipelines ------ */
  1111.  
  1112. /*
  1113.  * Add a filter to an output pipeline.  The client must have allocated the
  1114.  * stream state, if any, using the given allocator.  For s_init_filter, the
  1115.  * client must have called s_init and s_init_state.
  1116.  */
  1117. int
  1118. s_init_filter(stream *fs, stream_state *fss, byte *buf, uint bsize,
  1119.           stream *target)
  1120. {
  1121.     const stream_template *template = fss->template;
  1122.  
  1123.     if (bsize < template->min_in_size)
  1124.     return ERRC;
  1125.     s_std_init(fs, buf, bsize, &s_filter_write_procs, s_mode_write);
  1126.     fs->procs.process = template->process;
  1127.     fs->state = fss;
  1128.     if (template->init)
  1129.     (template->init)(fss);
  1130.     fs->strm = target;
  1131.     return 0;
  1132. }
  1133. stream *
  1134. s_add_filter(stream **ps, const stream_template *template,
  1135.          stream_state *ss, gs_memory_t *mem)
  1136. {
  1137.     stream *es;
  1138.     stream_state *ess;
  1139.     uint bsize = max(template->min_in_size, 256);    /* arbitrary */
  1140.     byte *buf;
  1141.  
  1142.     /*
  1143.      * Ensure enough buffering.  This may require adding an additional
  1144.      * stream.
  1145.      */
  1146.     if (bsize > (*ps)->bsize && template->process != s_NullE_template.process) {
  1147.     stream_template null_template;
  1148.  
  1149.     null_template = s_NullE_template;
  1150.     null_template.min_in_size = bsize;
  1151.     if (s_add_filter(ps, &null_template, NULL, mem) == 0)
  1152.         return 0;
  1153.     }
  1154.     es = s_alloc(mem, "s_add_filter(stream)");
  1155.     buf = gs_alloc_bytes(mem, bsize, "s_add_filter(buf)");
  1156.     if (es == 0 || buf == 0) {
  1157.     gs_free_object(mem, buf, "s_add_filter(buf)");
  1158.     gs_free_object(mem, es, "s_add_filter(stream)");
  1159.     return 0;
  1160.     }
  1161.     ess = (ss == 0 ? (stream_state *)es : ss);
  1162.     ess->template = template;
  1163.     ess->memory = mem;
  1164.     es->memory = mem;
  1165.     s_init_filter(es, ess, buf, bsize, *ps);
  1166.     *ps = es;
  1167.     return es;
  1168. }
  1169.  
  1170. /*
  1171.  * Close the filters in a pipeline, up to a given target stream, freeing
  1172.  * their buffers and state structures.
  1173.  */
  1174. int
  1175. s_close_filters(stream **ps, stream *target)
  1176. {
  1177.     while (*ps != target) {
  1178.     stream *s = *ps;
  1179.     gs_memory_t *mem = s->state->memory;
  1180.     byte *sbuf = s->cbuf;
  1181.     stream *next = s->strm;
  1182.     int status = sclose(s);
  1183.     stream_state *ss = s->state; /* sclose may set this to s */
  1184.  
  1185.     if (status < 0)
  1186.         return status;
  1187.     if (mem) {
  1188.         gs_free_object(mem, sbuf, "s_close_filters(buf)");
  1189.         gs_free_object(mem, s, "s_close_filters(stream)");
  1190.         if (ss != (stream_state *)s)
  1191.         gs_free_object(mem, ss, "s_close_filters(state)");
  1192.     }
  1193.     *ps = next;
  1194.     }
  1195.     return 0;
  1196. }
  1197.  
  1198. /* ------ NullEncode/Decode ------ */
  1199.  
  1200. /* Process a buffer */
  1201. private int
  1202. s_Null_process(stream_state * st, stream_cursor_read * pr,
  1203.            stream_cursor_write * pw, bool last)
  1204. {
  1205.     return stream_move(pr, pw);
  1206. }
  1207.  
  1208. /* Stream template */
  1209. const stream_template s_NullE_template = {
  1210.     &st_stream_state, NULL, s_Null_process, 1, 1
  1211. };
  1212. const stream_template s_NullD_template = {
  1213.     &st_stream_state, NULL, s_Null_process, 1, 1
  1214. };
  1215.